<?php

namespace App\Http\Controllers\Admin;

use App\Models\Node;
use App\Models\Role;
use Illuminate\Http\Request;

class RoleController extends BaseController
{
    //角色列表显示
    public function index()
    {
        $data = Role::orderBy('id', 'desc')->paginate($this->pagesize);
        return view('admin.role.index', compact('data'));
    }

    //角色添加显示
    public function create()
    {
        return view('admin.role.create');
    }

    //角色添加处理
    public function store(Request $request)
    {
        //表单验证
        $data = $this->validate($request, [
            'name' => 'required|min:2'
        ]);
        //数据入库
        Role::create($data);
        return redirect(route('admin.role.create'))->with('success', '添加角色成功');
    }

    //角色修改 路由隐式转换 路由参数中的名称要和方法中参数变量名一致
    public function edit(Role $role)
    {
        return view('admin.role.edit', compact('role'));
    }

    public function update(Request $request, Role $role)
    {
        $role->update(['name' => $request->get('name')]);
        return ['code' => 200, 'msg' => '修改角色成功', 'data' => $role];
    }

    //分配权限显示和处理
    public function auth(Request $request, Role $role)
    {
        if ($request->isMethod('post')) {
            $data = $request->get('auth_id');
            foreach ($data as $id) {
                $data[] = Node::where('id', $id)->first()->pid;
            }
            $data = array_unique($data);
            //多对多同步数据
            $role->nodes()->sync($data);
            return redirect(route('admin.role.index'));
        }
        //所有权限
        $nodeData = treeLevel(Node::get()->toArray());
        //多对多查询数据，查询当前角色拥有的权限
        $auths = $role->nodes()->pluck('id')->toArray();
        return view('admin.role.auth', compact('nodeData', 'role', 'auths'));
    }
}
